package com.anyikang.volunteer.sos.volunteer.app.main;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyApplication;
import com.anyikang.volunteer.sos.volunteer.utils.PermissionResultAdapter;
import com.anyikang.volunteer.sos.volunteer.utils.PermissionUtil;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;

import java.util.LinkedList;
import java.util.List;


/**
 * 主页框架，默认显示地图页
 */
public class MainActivity extends AppCompatActivity {
    FrameLayout flContainer;
    BottomNavigationBar bottomNavigationBar;
    private MainActivity mActivity;
    String TAG = "MainActivity";


    public static List<Activity> activityList = new LinkedList<Activity>(); //用于百度导航，避免重复打开导航地图页面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mActivity = this;
        ((MyApplication)this.getApplication()).addActivity(mActivity);

        //6.0权限申请
        PermissionUtil.getInstance().request(mActivity, new String[]{PermissionUtil.PERMISSION_ACCESS_COARSE_LOCATION,
                PermissionUtil.PERMISSION_ACCESS_FINE_LOCATION}, new PermissionResultAdapter() {
            @Override
            public void onPermissionDenied(String... permissions) {
                ToastUtils.showToast(MainActivity.this, "请打开定位权限");
            }
        });

        initView();
    }

    public void initView() {
        flContainer = (FrameLayout) this.findViewById(R.id.fl_container);
        bottomNavigationBar = (BottomNavigationBar) this.findViewById(R.id.bottom_navigation_bar);

        //初始化底部导航栏
        initBottomNavigationBar();
        //初始化第一个fragment
        initFirstFragment();
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        Log.e(TAG, "onNewINtent执行了");
        setIntent(intent);
        getIntent().putExtras(intent);
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "onResume");

        super.onResume();

       //gxw- bottomNavigationBar.selectTab(0);
    /*    List<Fragment> fragments = getSupportFragmentManager().getFragments();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragments != null)
        {


            for(int i = 0; i < fragments.size(); i++)
            {
                if(i == 0)
                {
                    transaction.show(fragments.get(i));
                    bottomNavigationBar.setFirstSelectedPosition(0); //设置默认显示第一个HOME TAB页
                }
                else
                {
                    transaction.hide(fragments.get(i));
                }

            }

            transaction.commitAllowingStateLoss();

        }*/


    }

/*    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG,"onActivityResult");
        if(requestCode == REQUEST_LOGIN)
        {

            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }*/

    /**
     * 初始化第一个fragment
     */
    private void initFirstFragment() {


        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragments != null && fragments.size() > 0) {
            //说明有之前缓存的fragment 处理fragment重影的问题
            for (int i = 0; i < fragments.size(); i++) {
                transaction.remove(fragments.get(i));
            }
            transaction.commit();
        }

        /*gxw+s防止白屏，因为当重复启动Mainactivity时，虽然homeFragment变量有值，实质Homefragment组件已被destroy，因此
          当 执行 transaction.add(R.id.fl_container, fragment, "0").commit();时，其实是添加了一个已经被销毁了的Homefragment，所以不会显示
          Homefragment的 view，会出现白屏
        **/
        FragmentFactory.homeFragment = null;
        FragmentFactory.sosListFragment = null;
        FragmentFactory.spotFragment = null;
        FragmentFactory.mineFragment = null;
       /*gxw+e防止白屏*/

        Fragment fragment = FragmentFactory.getFragment(0);
        transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_container, fragment, "0").commit();
    }

    /**
     * 初始化底部导航栏
     */
    private void initBottomNavigationBar() {
        //设置BottomNavigationBar的模式
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_SHIFTING);
        //设置BottomNavigationBar的背景风格
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        //BottomNavigationItem("底部导航icon","底部导航名字")
        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.tab_home1, R.string.tab_home))//设置选中时的颜色
                .addItem(new BottomNavigationItem(R.drawable.tab_sos1, R.string.tab_sos))
                .addItem(new BottomNavigationItem(R.drawable.tab_spot1, R.string.tab_spot))
                .addItem(new BottomNavigationItem(R.drawable.tab_mine1, R.string.tab_mine))
                .setBarBackgroundColor(R.color.white)//设置背景色
                 .setActiveColor(R.color.colorPrimary)//设置选中时的颜色
                 .setInActiveColor(R.color.color_unsel_gray)//设置没被选中时的颜色

                .setFirstSelectedPosition(0)//默认选择索引为0的菜单
                .initialise();//初始化


        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                //通过position拿到fragment
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                Fragment fragment = FragmentFactory.getFragment(position);
                if (fragment.isAdded()) {
                    //如果这个fragment 已经被add进来 显示一下
                    transaction.show(fragment).commit();
                } else {
                    //如果这个fragment 没有被add进来 那么把fragment add到主界面中
                    transaction.add(R.id.fl_container, fragment, position + "").commitAllowingStateLoss();
                }
            }

            @Override
            public void onTabUnselected(int position) {
                Log.e("MainActivity", "onTabUnselected" + position);
                //没被选中
                //通过position找到fragment隐藏起来
                getSupportFragmentManager().beginTransaction().hide(FragmentFactory.getFragment(position)).commit();
                getSupportFragmentManager().beginTransaction().commitAllowingStateLoss();//gxw+
            }

            @Override
            public void onTabReselected(int position) {
            }
        });
    }


    private long firstTime = 0;

    /**
     * 退出程序
     *
     * @param keyCode
     * @param event
     * @return
     */
   @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    //如果两次按键时间间隔大于2秒，则不退出
                    ToastUtils.showToast(MainActivity.this,"再次点击将退出程序，并且关闭定位");
                    firstTime = secondTime;//更新firstTime
                    return true;
                } else {
                    finish();
                    //两次按键小于2秒时，退出应用
                   //gxw-  System.exit(0); 会导致JPUSH收不到
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }
}
